package com.example.ymm.modules1.service.dd;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2DepartmentGetRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.response.OapiV2DepartmentGetResponse;
import com.example.ymm.exception.YmException;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class DdDeptInfoService {
    /**
     * 钉钉部门信息
     */
    @Autowired
    AccessTokenService2 accessTokenService;


    /**
     https://open.dingtalk.com/document/isvapp/query-department-details0-v2
     * 通过deptId 获取部门详情
     * @param deptId
     * @return
     */
    public JSONObject getByDeptId(String deptId){
        JSONObject json=null;
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
            String accessToken = accessTokenService.getAccessToken();

            OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
            req.setDeptId(Long.valueOf(deptId));
            req.setLanguage("zh_CN");
            OapiV2DepartmentGetResponse rsp = client.execute(req, accessToken);

            JSONObject result=JSONObject.parseObject(rsp.getBody());

            if("0".equals(result.getString("errcode"))){
                json=JSONObject.parseObject(result.getString("result"));
            }else{
                throw new YmException(result.getString("errmsg"));
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return json;
    }


}
